/**
   Copyright 2011 Фроловский А. В.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
   
   This file is a part of MyStats project
 */

package foo.mystats;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.text.format.DateFormat;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;
import foo.mystats.contentprovider.DataContentProvider;
import foo.mystats.db.DataTable;
import foo.mystats.db.RowTable;
import foo.mystats.model.DataType;

public class DataEditActivity extends Activity implements OnDateSetListener, OnTimeSetListener {
  private long rowId;
  private int dataType;
  private boolean isTimeNeeded;
  private GregorianCalendar dateTime;

  private EditText valueInteger;
  private EditText valueReal;
  private EditText valueString;
  private ToggleButton valueBoolean;
  private TimePicker valueDateTime;
  private Button dateButton;
  private Button timeButton;

  private Uri dataUri;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.setContentView(R.layout.data_edit);

    this.dateTime = new GregorianCalendar(TimeZone.getTimeZone("GMT+00"));
    this.dateTime.setTimeInMillis(0);

    initViews();

    Bundle extras = getIntent().getExtras();
    dataUri = (savedInstanceState == null) ? null : (Uri) savedInstanceState.getParcelable("data_uri");
    if (extras != null) {
      dataUri = extras.getParcelable("data_uri");
      if (dataUri != null) {
        fillData(dataUri);
      } else {
        this.rowId = extras.getLong(DataListActivity.PARAM_ROW_ID);
        this.dataType = extras.getInt(DataListActivity.PARAM_ROW_DATA_TYPE);
        this.isTimeNeeded = extras.getBoolean(DataListActivity.PARAM_ROW_IS_TIME_NEEDED);
        showOnlyValueForType(this.dataType);
        updateDateTime();
      }
    }
  }

  public void initViews() {
    valueInteger = (EditText) findViewById(R.id.data_edit_value_integer);
    valueReal = (EditText) findViewById(R.id.data_edit_value_real);
    valueString = (EditText) findViewById(R.id.data_edit_value_string);
    valueDateTime = (TimePicker) findViewById(R.id.data_edit_value_time);
    valueDateTime.setIs24HourView(DateFormat.is24HourFormat(getBaseContext()));
    valueBoolean = (ToggleButton) findViewById(R.id.data_edit_value_boolean);
    dateButton = (Button) findViewById(R.id.data_edit_button_date);
    timeButton = (Button) findViewById(R.id.data_edit_button_time);
  }

  public void onSaveClick(View v) {
    if (getValueAsString().trim().equals("")) {
      showAlert(R.string.msg_value_empty);
      return;
    }

    saveState();
    finish();
  }

  public String getValueAsString() {
    switch (this.dataType) {
      case DataType.INTEGER:
        return valueInteger.getText().toString();
      case DataType.REAL:
        return valueReal.getText().toString();
      case DataType.STRING:
        return valueString.getText().toString();
      case DataType.BOOLEAN:
        return String.valueOf(valueBoolean.isChecked() ? 1 : 0);
      case DataType.TIME:
        return String.valueOf(valueDateTime.getCurrentHour().intValue() * 3600 +
            valueDateTime.getCurrentMinute().intValue() * 60);
      default:
        return "";
    }
  }

  public void showOnlyValueForType(int dataType) {
    if (dataType == DataType.INTEGER) {
      valueInteger.setVisibility(View.VISIBLE);
      valueInteger.setText("");
    } else {
      valueInteger.setVisibility(View.GONE);
    }

    if (dataType == DataType.REAL) {
      valueReal.setVisibility(View.VISIBLE);
      valueReal.setText("");
    } else {
      valueReal.setVisibility(View.GONE);
    }

    if (dataType == DataType.STRING) {
      valueString.setVisibility(View.VISIBLE);
      valueString.setText("");
    } else {
      valueString.setVisibility(View.GONE);
    }

    if (dataType == DataType.TIME) {
      valueDateTime.setVisibility(View.VISIBLE);
      valueDateTime.setCurrentHour(0);
      valueDateTime.setCurrentMinute(0);
    } else {
      valueDateTime.setVisibility(View.GONE);
    }

    if (dataType == DataType.BOOLEAN) {
      valueBoolean.setVisibility(View.VISIBLE);
      valueBoolean.setChecked(true);
    } else {
      valueBoolean.setVisibility(View.GONE);
    }
  }

  public void onSetDateClick(View v) {
    new DatePickerDialog(this, this, dateTime.get(Calendar.YEAR), dateTime.get(Calendar.MONTH),
        dateTime.get(Calendar.DAY_OF_MONTH)).show();
  }

  public void onSetTimeClick(View v) {
    new TimePickerDialog(this, this, dateTime.get(Calendar.HOUR_OF_DAY),
        dateTime.get(Calendar.MINUTE), DateFormat.is24HourFormat(getBaseContext())).show();
  }

  @Override
  public void onDateSet(DatePicker datePicker, int year, int month, int day) {
    dateTime.set(Calendar.YEAR, year);
    dateTime.set(Calendar.MONTH, month);
    dateTime.set(Calendar.DAY_OF_MONTH, day);

    updateDateTime();
  }

  @Override
  public void onTimeSet(TimePicker timePicker, int hour, int minute) {
    dateTime.set(Calendar.HOUR_OF_DAY, hour);
    dateTime.set(Calendar.MINUTE, minute);

    updateDateTime();
  }

  private void saveState() {
    ContentValues values = new ContentValues();

    values.put(DataTable.COLUMN_ROW_ID, this.rowId);
    values.put(DataTable.COLUMN_VALUE, getValueAsString());

    Date date = new Date(dateTime.getTime().getTime());
    values.put(DataTable.COLUMN_DATETIME, date.getTime() / 1000);

    if (dataUri == null) {
      dataUri = getContentResolver().insert(DataContentProvider.CONTENT_URI, values);
    } else {
      getContentResolver().update(dataUri, values, null, null);
    }
  }

  private void fillData(Uri uri) {
    String[] projection = {
        DataTable.TABLE_DATA + "." + DataTable.COLUMN_ID + " AS " + BaseColumns._ID,
        DataTable.COLUMN_DATETIME + " AS " + DataTable.COLUMN_DATETIME,
        DataTable.COLUMN_VALUE + " AS " + DataTable.COLUMN_VALUE,
        DataTable.COLUMN_ROW_ID + " AS " + DataTable.COLUMN_ROW_ID,
        RowTable.COLUMN_DATA_TYPE + " AS " + RowTable.COLUMN_DATA_TYPE,
        RowTable.COLUMN_IS_TIME_NEEDED + " AS " + RowTable.COLUMN_IS_TIME_NEEDED,
    };

    Cursor c = getContentResolver().query(uri, projection, null, null, null);
    if (c != null) {
      c.moveToFirst();

      this.rowId = c.getInt(c.getColumnIndexOrThrow(DataTable.COLUMN_ROW_ID));
      this.dataType = c.getInt(c.getColumnIndexOrThrow(RowTable.COLUMN_DATA_TYPE));
      this.isTimeNeeded = c.getInt(c.getColumnIndexOrThrow(RowTable.COLUMN_IS_TIME_NEEDED)) == 1;
      this.dateTime.setTimeInMillis(c.getLong(c.getColumnIndexOrThrow(DataTable.COLUMN_DATETIME)) * 1000);

      showOnlyValueForType(this.dataType);

      updateDateTime();

      int valueColumnIndex = c.getColumnIndexOrThrow(DataTable.COLUMN_VALUE);

      switch (dataType) {
        case DataType.INTEGER:
          valueInteger.setText(String.valueOf(c.getInt(valueColumnIndex)));
          break;
        case DataType.REAL:
          valueReal.setText(String.valueOf(c.getDouble(valueColumnIndex)));
          break;
        case DataType.STRING:
          valueString.setText(c.getString(valueColumnIndex));
          break;
        case DataType.BOOLEAN:
          valueBoolean.setChecked(c.getInt(valueColumnIndex) == 1);
          break;
        case DataType.TIME:
          GregorianCalendar calendar = new GregorianCalendar();
          calendar.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
          calendar.setTimeInMillis(c.getLong(valueColumnIndex) * 1000);
          valueDateTime.setCurrentHour(Integer.valueOf(calendar.get(Calendar.HOUR_OF_DAY)));
          valueDateTime.setCurrentMinute(Integer.valueOf(calendar.get(Calendar.MINUTE)));
          break;
      }

      c.close();
    }
  }

  private void updateDateTime() {
    java.text.DateFormat myDateFormat = DateFormat.getLongDateFormat(getBaseContext());
    myDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
    dateButton.setText(myDateFormat.format(this.dateTime.getTime()));

    if (!this.isTimeNeeded) {
      timeButton.setVisibility(View.GONE);
    } else {
      timeButton.setVisibility(View.VISIBLE);

      java.text.DateFormat myTimeFormat = DateFormat.getTimeFormat(getBaseContext());
      myTimeFormat.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));

      timeButton.setText(myTimeFormat.format(this.dateTime.getTime()));
    }
  }

  public void showToast(int stringResId) {
    Toast toast = Toast.makeText(getApplicationContext(), stringResId, Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.CENTER, 0, 0);
    toast.show();
  }

  public void showAlert(int stringResId) {
    new AlertDialog.Builder(this).setMessage(stringResId).show();
  }

}
